/*
 * AdminFilter.java
 * 作用：管理员权限过滤器，确保只有拥有"admin"角色的用户才能访问后台管理页面（`/admin/*` 路径）。
 */
package com.campustradingwall.filter;

import com.campustradingwall.model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/admin/*")
public class AdminFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        // AuthenticationFilter已经确保用户已登录，这里只需检查角色
        User user = (session != null) ? (User) session.getAttribute("user") : null;

        if (user != null && "admin".equals(user.getRole())) {
            // 用户是管理员，继续处理请求
            chain.doFilter(request, response);
        } else {
            // 用户不是管理员或未登录，重定向到首页
            response.sendRedirect(request.getContextPath() + "/");
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Filter初始化代码
    }

    @Override
    public void destroy() {
        // Filter销毁代码
    }
} 